package cn.e4j.modular.system.controller;

import cn.e4j.core.base.controller.BaseController;
import cn.e4j.core.dto.Dtos;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.reqres.response.ErrorResponseData;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.shiro.ShiroKit;
import cn.e4j.core.shiro.ShiroUser;
import cn.e4j.core.shiro.UserPasswordToken;
import cn.e4j.core.util.HttpContext;
import cn.e4j.modular.system.entity.SysUser;
import cn.e4j.modular.system.mapper.SysUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 登录控制器
 *
 * @author wenchuan.li
 * @Date 2018/01/10 下午8:25:24
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 跳转到主页
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {

        ShiroUser user = ShiroKit.getUser();
        if (user == null) {
            return "/login";
        }
        //获取菜单列表
//        List<Integer> roleList = ShiroKit.getUser().getRoleList();
//        if (roleList == null || roleList.size() == 0) {
//            ShiroKit.getSubject().logout();
//            model.addAttribute("tips", "该用户没有角色，无法登陆");
//            throw new UndeclaredThrowableException(null, "该用户没有角色，无法登陆");
//            //return "/login";
//        }
        //List<MenuNode> menus = menuService.getMenusByRoleIds(roleList);
        //List<MenuNode> titles = MenuNode.buildTitle(menus);
        //titles = ApiMenuFilter.build(titles);

        //model.addAttribute("titles", titles);

        //获取用户头像
//        Integer id = Integer.valueOf(ShiroKit.getUser().getId());
//        User user = userService.getById(id);
//        String avatar = user.getAvatar();
//        model.addAttribute("avatar", avatar);

        return REDIRECT + "/index";
    }

    /**
     * 跳转到登录页面
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        if (ShiroKit.isAuthenticated() || ShiroKit.getUser() != null) {
            return REDIRECT + "/index";
        } else {
            return "/pc/login.html";
        }
    }

    /**
     * session实效调用
     */
    @RequestMapping(value = "/relogin", method = RequestMethod.GET)
    public String relogin() {
        return "/pc/relogin.html";
    }

    /**
     * 点击登录执行的动作
     */
    @RequestMapping(value = "/toLogin", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData loginVali(@DtoParam DtoWapper dtow) {
        Dto dto = dtow.getDto();
        String username = dto.getString("username").trim();
        String password = dto.getString("password").trim();

        //验证验证码是否正确
//        if (KaptchaUtil.getKaptchaOnOff()) {
//            String kaptcha = super.getPara("kaptcha").trim();
//            String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
//            if (ToolUtil.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)) {
//                throw new InvalidKaptchaException();
//            }
//        }

//        Subject currentUser = ShiroKit.getSubject();
//        UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());
//
//        if ("on".equals(remember)) {
//            token.setRememberMe(true);
//        } else {
//            token.setRememberMe(false);
//        }
//
//        currentUser.login(token);

        String lang_ = "zh_CN";
        String dbc_ = "80";
        String site_ = null;
        boolean rememberMe = dto.getBoolean("remember");
        String host = HttpContext.getIp();
        String captcha = "";
        boolean mobile = false;
        UserPasswordToken userPasswordToken = new UserPasswordToken(username, password.toCharArray(), rememberMe, host, captcha, mobile,
                lang_, dbc_, site_);
        Subject subject = ShiroKit.getSubject();
        try {
            subject.login(userPasswordToken);

            ShiroUser shiroUser = ShiroKit.getUser();
            super.getSession().setAttribute("shiroUser", shiroUser);
            super.getSession().setAttribute("username", shiroUser.getACCOUNT());

            //LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getID(), HttpContext.getIp()));

            ShiroKit.getSession().setAttribute("sessionFlag", true);
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR_TIP;
        }
        return SUCCESS_TIP;
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData logOut() {
        //LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getID(), HttpContext.getIp()));
        ShiroKit.getSubject().logout();
        deleteAllCookie();
        return SUCCESS_TIP;
    }

    @ResponseBody
    @RequestMapping(value = "updateMyPwd")
    public ResponseData updateMyPwd(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        Dto outDto = Dtos.newDto();
        if (!StringUtils.equals(inDto.getString("confirm_new_password_"), inDto.getString("new_password_"))) {
            return new ErrorResponseData(1005, "两次密码不一致");
        } else {
            ShiroUser user = ShiroKit.getUser();
            SysUser sysUser = sysUserMapper.selectById(user.getID());
            if (!StringUtils.equals(sysUser.getPASSWORD(), ShiroKit.md5(inDto.getString("password_")))) {
                return new ErrorResponseData(1006, "原密码输入错误，请确认。");
            } else {
                sysUser.setPASSWORD(ShiroKit.md5(inDto.getString("new_password_")));
                sysUser.updateById();
            }
        }
        return SUCCESS_TIP;
    }

    @ResponseBody
    @RequestMapping(value = "getUser")
    public Dto getUser(@DtoParam DtoWapper dtoWapper) {
        Dto outDto = Dtos.newDto();
        ShiroUser user = ShiroKit.getUser();
        SysUser sysUser = sysUserMapper.selectById(user.getID());

        outDto.put("data", sysUser);
        return outDto;
    }

    @ResponseBody
    @RequestMapping(value = "updateMyInfo")
    public ResponseData updateMyInfo(SysUser sysUser) {
        Dto outDto = Dtos.newDto();
        if (!sysUser.getACCOUNT().equals("admin")) {
            sysUser.setPASSWORD(null);
            sysUser.updateById();
        }
        return SUCCESS_TIP;
    }
}
